<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1400" destroy-on-close :close-on-press-escape="mode != 'show' ? false : true" @closed="$emit('closed')" align-center>
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm" style="height:700px;overflow:auto;">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item :label="$t('finance.receivecode')" prop="collect_code">
                        <el-input v-model="form.collect_code" :placeholder="$t('all.enter')" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('sale.client.client')" prop="customer_id">
                        <el-select v-model="form.customer_id" filterable clearable :placeholder="$t('all.select')" style="width:100%" disabled>
                            <el-option v-for="item in clientList" :key="item.id" :label="item.customer_name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                <el-form-item :label="$t('finance.receivedate')" prop="business_date">
                    <el-date-picker v-model="form.business_date" type="date" :placeholder="$t('all.select')" style="width: 100%;" :value-format="'YYYY-MM-DD'"></el-date-picker>
                </el-form-item>
                </el-col>
            </el-row>
            <el-col :span="12">
                <el-form-item :label="$t('finance.settlement')" prop="detail">
                    <sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" :placeholder="$t('all.noData')" height="180" show-summary @sons="accInput">
                        <el-table-column :label="$t('finance.account')" align="center">
                            <template #default="scope">
                                <el-select v-model="scope.row.settlement_id" :placeholder="$t('all.select')" filterable>
                                    <el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id"/>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('finance.receivemoney')" prop="money" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.money" :placeholder="$t('finance.receivemoney')" @input="accInput"></el-input>
                            </template>
                        </el-table-column>
                    </sc-form-table>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item :label="$t('finance.receiveorder')" prop="accounts_all">
                    <el-button type="primary" size="small" icon="el-icon-plus" @click="checkOrder">{{$t('finance.selectreceiveorder')}}</el-button>
                    <sc-form-table ref="table" v-model="form.accounts_all" :addTemplate="accounts_all" :placeholder="$t('all.noData')" height="300" hideAdd show-summary @sons="orderInput">
                        <el-table-column :label="$t('finance.businessdate')" prop="business_date" align="center"></el-table-column>
                        <el-table-column :label="$t('finance.orderdate')" prop="contract_code" align="center"></el-table-column>
                        <el-table-column :label="$t('finance.businesstype')" prop="type" align="center">
                            <template #default="scope">
                                {{scope.row.type == 1?$t('finance.saleorder'):scope.row.type == 2?$t('finance.salesreturn'):$t('finance.other')}}
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('finance.dentall')" prop="all_money" align="center"></el-table-column>
                        <el-table-column :label="$t('finance.recoveredall')" prop="pay_money" align="center"></el-table-column>
                        <el-table-column :label="$t('finance.receivableall')" prop="only_money" align="center"></el-table-column>
                        <!-- <el-table-column label="当前欠款" prop="all_only_money" align="center"></el-table-column> -->
                        <el-table-column :label="$t('finance.collection')" prop="money" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.money" :placeholder="$t('finance.collection') + ('(RMB)')" clearable @input="orderInput"></el-input>
                            </template>
                        </el-table-column>
                    </sc-form-table>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item :label="$t('all.remark')" prop="remark">
                <el-input v-model="form.remark" :placeholder="$t('all.remark')" type="textarea"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item :label="$t('all.attachment')" prop="enclosure">
                <sc-upload-file v-model="form.enclosure" :limit="1">
                    <el-button type="primary" icon="el-icon-upload">{{$t('all.selectattachment')}}</el-button>
                </sc-upload-file>
                </el-form-item>
            </el-col>
        </el-form>
        <template #footer>
            <el-button @click="visible=false">{{$t('all.cancel')}}</el-button>
            <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">{{$t('all.save')}}</el-button>
        </template>
    </el-dialog>
    <save-dialog v-if="dialog.detail" ref="detailDialog" @success="handleSuccess" @closed="dialog.detail = false" :query="{customer_id:this.form.customer_id}"></save-dialog>
</template>

<script>
import saveDialog from './save'

export default {
  components: {
    saveDialog,
  },
  emits: ['success', 'closed'],
  data() {
    return {
      mode: "add",
      titleMap: {
        add: '新增',
        edit: this.$t('finance.receive'),
        show: '查看'
      },
      visible: false,
      isSaveing: false,
      dialog: {
        detail: false,
      },
      form: {
        business_date: this.moment().format('YYYY-MM-DD'),
        collect_code: "",
        customer_id: "",
        money: "",
        remark: "",
        enclosure: "",
        status: 1,
        accounts_all: [],
        detail: [],
      },
      addTemplate: {},
      accounts_all: {},
      accountList: [],    //账户
      clientList: [],     //客户
      countorder: "",
    }
  },
  mounted() {
    this.getAccount()
    this.getClient()
  },
  methods: {
    //显示
    open(mode = 'add') {
      this.mode = mode;
      this.visible = true;
      return this
    },
    //表单提交方法
    submit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          if (this.form.money != this.countorder) {
            this.$alert("本次收款金额与单据金额不相等，请确认", this.$t('all.prompt'), {type: "error"})
          } else {
            this.isSaveing = true;
            var res = await this.$API.finance.shouorder.add.post(this.form);
            this.isSaveing = false;
            if (res.code == 1) {
              this.$emit('success', this.form, this.mode)
              this.visible = false;
              this.$message.success(this.$t('all.yes'))
            } else {
              this.$alert(res.message,this.$t('all.prompt'), {type: "error"});
            }
          }
        }
      })
    },
    //表单注入数据
    setData(data) {
      this.form.id = data.id
      this.form.customer_id = data.customer_id
    },
    // 账号
    async getAccount() {
      var res = await this.$API.finance.account.all.get();
      this.accountList = res.data;
    },
    // 客户
    async getClient() {
      var res = await this.$API.client.client.all.get();
      this.clientList = res.data;
    },
    checkOrder() {
      this.dialog.detail = true
      this.$nextTick(() => {
        this.$refs.detailDialog.open('add')
      })
    },
    handleSuccess(data) {
      let array = []
      data.map(item => {
        array.push({
          accounts_id: item.id,
          business_date: item.business_date,
          contract_code: item.contract && item.contract.contract_code,
          all_money: item.money,
          pay_money: item.pay_money,
          only_money: item.only_money,
          remark: item.remark,
          money: item.only_money,
          type: item.type,
        })
      })
      let existingIds = this.form.accounts_all.map(item => item.accounts_id);
      for (let i = array.length - 1; i >= 0; i--) {
        if (existingIds.includes(array[i].accounts_id)) {
          array.splice(i, 1);
        }
      }
      this.form.accounts_all = [...this.form.accounts_all, ...array]
      this.orderInput()
    },
    accInput() {
      let count_price = 0
      this.form.detail.map(item => {
        if (item.money) {
          count_price = Number(count_price) + Number(item.money)
        }
      })
      this.form.money = count_price
    },
    orderInput() {
      let count_price = 0
      this.form.accounts_all.map(item => {
        if (item.money) {
          count_price = Number(count_price) + Number(item.money)
        }
      })
      this.countorder = count_price
    },
  }
}
</script>

<style>
</style>
